package com.wft.chapter15;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class FileChannelTest {
    public static void main(String[] args) {
        File file = new File("D:\\Workspaces2018\\crazy-java\\src\\main\\java\\com\\wft\\chapter15\\FileChannelTest.java");
        try (
            FileChannel inChannel = new FileInputStream(file).getChannel();
            FileChannel outChannel = new FileOutputStream("a.txt").getChannel();
        ) {
            // 将inChannel里的全部数据映射成ByteBuffer
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            // 使用UTF-8的字符集来创建解码器
            Charset charset = Charset.forName("UTF-8");
            // 直接将buffer里的数据全部输出
            outChannel.write(buffer);
            // 调用clear方法，复原limit、position的位置
            buffer.clear();
            // 创建解码器对象
            CharsetDecoder decoder = charset.newDecoder();
            // 使用解码器将ByteBuffer转换成CharBuffer
            CharBuffer charBuffer = decoder.decode(buffer);
            System.out.println(charBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}